const publicClass = require('../module/publicClass.js')
const {
	signtoken
} = require('../module/Token.js')
// 登录
class userlogin extends publicClass {
	constructor(req, res, neth) {
		super(req, res, neth)
		this.reginfo()
	}
	reginfo() {
		var {
			uname,
			password
		} = this.req.body
		if (!uname) return this.sendform(0, '请提供用户名')
		if (!password) return this.sendform(0, '请提供登录密码')
		this.onload(uname, password)
	}
	onload(uname, password) {
		var sql = 'select userhouse_id,user_type from user_tabs where uname=? and password=?'
		this.query(sql, [uname, password]).then(res => {
			try {
				if (!res.length) return this.sendform(0, '账号或密码错误')
				this.sendform(1, 'success', {
					token: signtoken({
						...res[0]
					}),
					type: res[0].user_type
				})
			} catch (err) {
				this.neth(err)
			}
		}, err => this.neth(err))
	}
}
// 获取业主信息 分页+模糊查询
class getuserinfo extends publicClass {
	constructor(req, res, neth) {
		super(req, res, neth)
		this.regtoken()
	}
	async onload(data) {
		try{
			if (data.user_type != 1) return this.sendform(0, '没有权限', )
			var {
				page,
				pageNum,
				search
			} = this.req.query
			page=parseInt(page<1?1:page)
			pageNum=parseInt(pageNum)
			if(!search)search={}
			// 分页开始位置
			let startPosition=parseInt((page-1)*pageNum)
			let countSql = `SELECT COUNT(_id) AS count FROM house_tab`;
			// 总页数
			let pageCont=await this.query(countSql,[])
			let total=pageCont[0].count
			pageCont= Math.ceil(pageCont[0].count / pageNum);
			var sql = `select 
					sex,race,birthplace,jointime,idno,phone,house_id,house_num,
					house_name,house_numLD,house_sum,vaccination,house_vehicleSum,house_remark from house_tab ORDER BY house_updateTime DESC `
			// 遍历需要进行搜索的字段
			let LIKESTR=''
			let objKey=Object.keys(search)
			objKey.forEach((Key,index)=>{
				let str=` ${Key} LIKE "%${search[Key]}%" `
				if(index+1!=objKey.length)str+='and'
				LIKESTR+=str
			})
			let sqlArr=[startPosition,pageNum]
			if(objKey.length){
				sql+=' where'
				sql+=LIKESTR
				sql+=' LIMIT ?,?'
			}else{
				sql+=' LIMIT ?,?'
			}
			this.query(sql,sqlArr).then(res=>{
				let data={
					page,
					pageNum,
					pageCont,
					total,
					items:res
				}
				this.sendform(1, 'success', data)
			},err => this.neth(err))
		}catch(err){
			this.neth(err)
		}
	}
}
// 添加住户
class addtoUser extends publicClass {
	constructor(req, res, neth) {
		super(req, res, neth)
		this.regtoken()
	}
	reginfo(){
	}
	async onload(){
		try{
			// 如果有户主编号则为修改
			if(this.req.body.house_id)return this.updateInfo()
			// 生成用户编号
			let {generationNumber,toTimeString} = require('../util/util.js')
			let data=this.req.body
			// 查询当前添加的用户门牌号是否存在,楼栋号+门牌号是唯一的
			var sql='select _id from house_tab where  house_numLD=? and house_num=?'
			let info=await this.query(sql,[data.house_numLD,data.house_num])
			if(info.length)return this.sendform(0,'该楼栋用户已存在,请核对信息是否有误')
			var sql='select _id from user_tabs where uname=? and user_type=?'
			let user=await this.query(sql,[data.phone,1])
			if(user.length)return this.sendform(0,'该手机号添加的住户账号已存在')
			// 住户编号,唯一性
			let house_id=generationNumber()
			// 添加住户登录账号, 账号为手机号码,初始密码密码为身份证后6位
			let objinfo={
				uname:data.phone,
				password:data.idno.substring(data.idno.length-6),
				userhouse_id:house_id,
				user_type:2
			}
			var sql = "INSERT INTO user_tabs SET ?";
			let addto=await this.query(sql,objinfo)
			if(addto.affectedRows<1)return this.sendform(0,'住户账号写入失败')
			// 写入该账号的住户信息
			data.house_id=house_id
			data.house_createTime=toTimeString(Date.now())
			data.house_updateTime=toTimeString(Date.now())
			var sql = "INSERT INTO house_tab SET ?";
			let addtoUser=await this.query(sql,data)
			// 住户数据写入失败时,删除已添加的当前住户已添加的登录账户
			if(addtoUser.affectedRows<1){
				this.query('delete from user_tabs where house_id=?',house_id).then(res=>console.log('删除成功'),err=>console.log('删除失败'))
				return this.sendform(0,'住户信息写入失败')
			}
			this.sendform(1,'success',data)
		}catch(err){
			this.neth(err)
			throw err
		}
	}
	updateInfo(){
		let data={...this.req.body}
		let {toTimeString} = require('../util/util.js')
		data.house_updateTime=toTimeString(Date.now())
		let id=data.house_id
		delete data.house_id
		var sql='update house_tab set ? where house_id=?'
		this.query(sql,[data,id]).then(res=>{
			this.sendform(1,'成功')
		})
	}
}
// 删除
class delhome extends publicClass{
	constructor(req, res, neth) {
		super(req, res, neth)
		this.regtoken()
	}
	reginfo(){
		if(!this.req.body.id) return this.sendform(0,'业主编号不能为空')
		return true
	}
	async onload(){
		if(!this.reginfo())return
		var sql='delete from house_tab where house_id=?'
		await this.query(sql,this.req.body.id).then(res=>{
			this.query('delete from user_tabs where userhouse_id=?',this.req.body.id).then(res=>{
				if(res.affectedRows>0)this.sendform(1,'删除成功')
			})
		})
	}
}





module.exports = {
	userlogin,
	getuserinfo,
	addtoUser,
	delhome
}
